import java.util.ArrayList;
import java.util.Arrays;

public class MyHeap {
    public int[] elem = new int[10];
    public int usedSize;

    public MyHeap(int[] elem) {
        this.elem = elem;
        usedSize = elem.length;
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param
     */
    public void createHeap() {
        int parent = 0;
        shiftDown(parent);
    }
    private void swap(int parent,int child) {
        if (child >= usedSize) return;
        if (elem[parent]>elem[child]) {
            int tamp = elem[parent];
            elem[parent] = elem[child];
            elem[child] = tamp;
        }
    }

    /**
     *
     *  是每棵子树的根节点的下标
     *   是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int parent) {
        int child = (parent*2)+1;
        for ( ;parent < usedSize;parent++) {
            while (child < usedSize && parent < usedSize) {
                child = (parent * 2) + 1;
                swap(parent, child);
                if (child + 1 < usedSize && elem[child + 1] > elem[child]) {
                    break;
                } else {
                    swap(child,child + 1);
                    parent++;
                }
            }
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if (usedSize == elem.length) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize - 1);
    }
    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0) {
            if (elem[child] > elem[parent]) {
                break;
            }else {
                swap(parent,child);
            }
            child = parent;
            parent = (child - 1) / 2;
        }
    }

    public boolean isFull() {
        return true;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        for (int i = 0; i < usedSize; i++) {
            elem[i] = elem[i+1];
        }
        usedSize--;
        shiftDown(usedSize);
    }

    public boolean isEmpty() {
        if (usedSize == 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if (usedSize == 0) {
            return -1;
        }
        return elem[0];
    }
}